<template>
  <div style="padding: 10px;overflow-y: auto;">
    <div class="header-btn">
      <div>{{ this.id ? '编辑' : '创建' }}文章</div>
      <div>
        <el-button :loading="loading" type="primary" @click="confirm">确认</el-button>
        <el-button plain type="info" @click="back">返回</el-button>
      </div>
    </div>
    <el-row style="background-color: #fff;padding: 20px;border-radius: 8px;">
      <el-col :lg="18" :md="20" :sm="22" :xl="16" :xs="24">
        <el-form ref="form" label-position="right" label-width="100px">
          <el-form-item label="文章类型" required>
            <el-radio-group v-model="form.verbalType">
              <el-radio :label="1">原创文章</el-radio>
              <el-radio :label="2">转载文章</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.verbalType === 2" label="转载链接" required>
            <p style="color: #b2b2b2;">为避免侵权，请注明转载来源</p>
            <!-- 您录入字数超过320字 -->
            <el-input v-model="form.catchUrl" placeholder="请输入公众号文章链接">
              <el-button slot="append" :loading="zhuaquLoading"
                         style="color: #909399 !important;background-color: #fff;"
                         @click="zhuaquBtn">获取文章
              </el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="文章标题" required>
            <el-input v-model="form.materialName" :disabled="form.verbalType == 2" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="来源/作者">
            <el-input v-model="form.author" :disabled="form.verbalType == 2" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="时间">
            <el-row>
              <el-checkbox v-model="timeFlag" label="显示时间" name="time" style="margin-right: 20px;"></el-checkbox>
              <el-date-picker v-model="form.articleCreateTime" :disabled="!timeFlag" placeholder="请选择"
                              type="datetime"></el-date-picker>
            </el-row>
          </el-form-item>
          <el-form-item label="个人分组" required>
            <el-select v-model="form.categoryId" placeholder="请输入" style="width: 100%;">
              <el-option v-for="item in personGroup" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容" required>
            <el-button @click="uploadDocx" style="margin-bottom: 6px">
              <svg-icon iconClass="upload-simple"></svg-icon>
              <span class="ml5"> 上传word文档</span>
            </el-button>
            <input class="inputFile" ref="fileInput" type="file" @change="uploadAndParseWord" accept=".docx" style="display: none"/>
            <!--                        <Tiny v-model="form.content"></Tiny>-->
            <WangEditor :value="form.content" @change="changeWang"></WangEditor>
            <!--            <Quill v-model="form.content"></Quill>-->
            <!--            <CKEditor editorId="editor1" ref="editor1"></CKEditor>-->
          </el-form-item>
          <el-form-item label="封面" required>
            <el-upload :before-upload="beforeUpload" :show-file-list="false" action class="avatar-uploader1">
              <i v-if="!form.materialUrl" class="el-icon-plus avatar-uploader-icon"></i>
              <el-image v-else :src="form.materialUrl" fit="contain" style="width: 178px;height: 178px"></el-image>
            </el-upload>
            <span class="suggestion">建议上传800*800像素的图片</span>
          </el-form-item>
          <el-form-item label="摘要">
            <el-input v-model="form.digest" placeholder="请输入" type="textarea"></el-input>
          </el-form-item>
          <el-form-item v-if="this.$route.query.is_person == 1" label="其他设置">
            <el-checkbox v-model="form.isSyncToEnterprise" :false-label="'0'" :true-label="'1'"
                         label="同步到企业文章库">
            </el-checkbox>
          </el-form-item>
          <el-form-item label="打标签">
            <tag-group v-model="form.tagVOS"/>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <MakeLabel :label.sync="tags" :visible.sync="tagVisible" @confirm="handleAddTag"></MakeLabel>
  </div>
</template>

<script>
import {
  addMaterial,
  articleEdit,
  articleEditCorp,
  articleInfo,
  catchArticle,
  categoryList,
  uploadFile
} from '@/api/article/group'
import {dateFormat} from '@/utils'
import Tiny from './components/tiny'
import MakeLabel from "@/components/MakeLabel/index.vue";
import WangEditor from "@/components/wangEditor/index.vue";
import mammoth from 'mammoth';
import {uploadInterface} from "@/api/operate/verbalTrick";

export default {
  name: 'Edit',
  components: {Tiny, MakeLabel, WangEditor,},
  data() {
    return {
      loading: false,
      zhuaquLoading: false,
      id: '',
      rich: '',
      tags: '',
      tagVisible: false,
      personGroup: [],
      companyGroup: [],
      timeFlag: false,
      other: [],
      form: {
        catchUrl: '',
        verbalType: 1,
        materialName: '',
        author: '',
        articleCreateTime: '',
        categoryId: '',
        levelId: '',
        content: '',
        materialUrl: '',
        digest: '',
        isSyncToEnterprise: '1',
        isAutoLabel: '0',
        materialTag: [],
        tagVOS: [],
        levelType: ''
      },
      oldUrl: '',
      wordImageList: [],
    }
  },
  created() {
    this.init()
    console.log(this.$route.query)
    if (this.$route.query.hasOwnProperty('id')) {
      this.id = this.$route.query.id
      this.getInfo(this.id)
    }
    console.log(this.$route, 'route', '@@@@@@#############')
  },
  methods: {
    uploadDocx(){
      this.$refs.fileInput.click()
    },
    async uploadAndParseWord(event) {
      const file = event.target.files[0];
      console.log(event.target.files[0], 'event')
      if(event.target.files[0]?.type !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') return this.$message.error('仅支持上传docx文档')
      if (file) {
        const arrayBuffer = await this.readFileAsArrayBuffer(file);
        try {
          const result = await mammoth.convertToHtml({arrayBuffer: arrayBuffer});
          this.uploadImagesFromHtml(result.value);
        } catch (error) {
          console.error('解析 Word 文档时发生错误:', error);
        }
      }
    },

    async uploadImagesFromHtml(html) {
      let content = JSON.parse(JSON.stringify(html));
      const imageRegex = /<img[^>]+src="data:image\/(.*?);base64,(.*?)"[^>]*>/g;
      let imageUrls = new Array();
      let match;
      let index = 0;
      while ((match = imageRegex.exec(content)) !== null) {
        let obj = {
          index: index,
          imageBase64: 'data:image/' + match[1] + ';base64,' + match[2],
          state: true,
          url: undefined,
          imageType: match[1]
        };
        imageUrls.push(obj);
        index++;
          // const res = await uploadInterface(formData);
          // if (res.code === 200) {
          //   const updatedItem = imageUrls.find((img) => img.index === obj.index && obj.state);
          //   if (updatedItem) {
          //     updatedItem.state = false;
          //     updatedItem.url = res.data.url;
          //   }
          // }
      }

      let indexObjMap = {};
      await this.recursiveUpload(imageUrls, indexObjMap);
      console.log(imageUrls, 'imageUrls1234567890987654321234567890987654321')

      imageUrls.forEach((item) => {
        if (item.url) {
          content = content.replaceAll(item.imageBase64, item.url);
        }
      });

      this.form.content = content;
      this.$refs.fileInput.value = null
    },

    async recursiveUpload(imageUrls, indexObjMap) {
      for (let obj of imageUrls) {
        if (obj.state) {
          const formData = new FormData();
          formData.append('index', obj.index)
          formData.append('file', this.base64ToBlob(obj.imageBase64, obj.imageType))
          formData.append('imageType', obj.imageType)
          const res = await uploadInterface(formData);

          if (res.code === 200) {
            obj.state = false;
            obj.url = res.data.url;
            // 更新对象映射
            indexObjMap[obj.index] = obj;
            // 递归调用自身
            await this.recursiveUpload(imageUrls, indexObjMap);
          }
        }
      }
    },

    base64ToBlob(base64Data, contentType) {
      console.log(base64Data, contentType, 'base64')
      const byteCharacters = atob(base64Data.split(',')[1]);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      return new Blob([byteArray], {type: contentType});
    },

    readFileAsArrayBuffer(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event) => {
          resolve(event.target.result);
        };
        reader.onerror = (error) => {
          reject(error);
        };
        reader.readAsArrayBuffer(file);
      });
    },
    init() {
      categoryList({
        levelType: 0,
        mediaType: 4
      }).then(res => {
        if (res.code === 200) {
          const {data} = res
          this.companyGroup = data
        }
      })
      categoryList({
        levelType: 1,
        mediaType: 4
      }).then(res => {
        if (res.code === 200) {
          const {data} = res
          this.personGroup = data
        }
      })
    },
    getInfo(id) {
      articleInfo(id).then(res => {
        if (res.code === 200) {
          const {data} = res
          if (data.articleCreateTime) {
            this.timeFlag = true
          }

          // let data = JSON.parse(JSON.stringify(row))
          if (data.tagVOS) {
            data.tagVOS1 = JSON.parse(JSON.stringify(data.tagVOS))
            data.tagVOS = []
            data.tagVOS1.forEach(tagGroup => {
              tagGroup.tagName.split(',').forEach(tagName => {
                data.tagVOS.push({groupName: tagGroup.groupName, tagName})
              })
            })
          }

          this.form = {
            catchUrl: data.title,
            verbalType: data.verbalType || 1,
            materialName: data.materialName,
            author: data.author || '',
            articleCreateTime: data.articleCreateTime ? (new Date(data.articleCreateTime)) : '',
            categoryId: data.categoryId,
            content: data.content,
            materialUrl: data.materialUrl,
            digest: data.digest,
            isSyncToEnterprise: data.isSync,
            isAutoLabel: '1',
            tagVOS: data.tagVOS || [],
            levelType: data.levelType
          }
          this.oldUrl = this.form.catchUrl
        }
      })
    },
    confirm() {
      this.addArticle()
    },
    zhuaquBtn() {
      if (this.form.catchUrl) {
        if (this.oldUrl != this.form.catchUrl) {
          this.form.content = ''
          this.form.materialName = ''
          this.form.author = ''
          this.form.materialUrl = ''
          this.oldUrl = this.form.catchUrl
        }
        this.zhuaquLoading = true;
        this.catchArticleFn()
      } else this.$message.error('请输入链接！')
    },
    catchArticleFn(response) {
      const _this = this;
      if (!response) {
        catchArticle({code: this.form.catchUrl}).then(res => {
          if (res.code === 200) {
            if (res.data) {
              this.zhuaquLoading = false;
              this.$message.success(res.msg)
              this.form.content = res.data.text
              this.form.materialName = res.data.title
              this.form.author = res.data.name
              this.form.materialUrl = res.data.cover
              return null;
            }
            let timer = setInterval(() => {
              clearInterval(timer);
              return _this.catchArticleFn(response);
            }, 2000);
          }
        }).catch(() => {
          console.log('失败！')
          this.zhuaquLoading = false;
        })
      }
    },
    addArticle() {
      if (this.form.materialName == '') {
        return this.$message.error('请输入文章标题')
      }
      if (this.timeFlag && (this.form.articleCreateTime == '' || this.form.articleCreateTime == null)) {
        return this.$message.error('请选择时间')
      }
      if (this.form.categoryId == '') {
        return this.$message.error('请选择个人分组')
      }
      if (this.form.content == '') {
        return this.$message.error('请输入内容')
      }
      if (this.form.materialUrl == '') {
        return this.$message.error('请选择封面')
      }
      this.loading = true
      if (this.id) {
        if (this.$route.query.name == 'one') {
          articleEditCorp({
            id: this.id,
            categoryId: this.form.categoryId,
            title: this.form.catchUrl,
            materialUrl: this.form.materialUrl,
            materialName: this.form.materialName,
            digest: this.form.digest,
            content: this.form.content,
            // levelId: this.form.levelId,
            levelType: this.form.levelType,
            author: this.form.author,
            // materialTag: this.form.materialTag ? this.form.materialTag.join('；') : '',
            tagVOS: this.form.tagVOS,
            mediaType: '4',
            articleCreateTime: this.timeFlag ? dateFormat(this.form.articleCreateTime) : null,
            isSyncToEnterprise: this.form.isSyncToEnterprise,
            isAutoLabel: '1'
          }).then(res => {
            this.loading = false
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.back()
            }
          }).catch(() => {
            this.loading = false
          })
        } else {
          articleEdit({
            id: this.id,
            categoryId: this.form.categoryId,
            title: this.form.catchUrl,
            materialUrl: this.form.materialUrl,
            materialName: this.form.materialName,
            digest: this.form.digest,
            content: this.form.content,
            // levelId: this.form.levelId,
            levelType: this.form.levelType,
            author: this.form.author,
            // materialTag: this.form.materialTag.join('；'),
            tagVOS: this.form.tagVOS,
            mediaType: '4',
            articleCreateTime: this.timeFlag ? dateFormat(this.form.articleCreateTime) : null,
            isSyncToEnterprise: this.form.isSyncToEnterprise,
            isAutoLabel: '1'
          }).then(res => {
            this.loading = false
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.back()
            }
          }).catch(() => {
            this.loading = false
          })
        }

      } else {
        addMaterial({
          categoryId: this.form.categoryId,
          title: this.form.catchUrl,
          materialUrl: this.form.materialUrl,
          verbalType: this.form.verbalType,
          materialName: this.form.materialName,
          digest: this.form.digest,
          content: this.form.content,
          // levelId: this.form.levelId,
          levelType: '1',
          author: this.form.author,
          // materialTag: this.form.materialTag.join('；'),
          tagVOS: this.form.tagVOS,
          mediaType: '4',
          articleCreateTime: this.timeFlag ? dateFormat(this.form.articleCreateTime) : null,
          isSyncToEnterprise: this.form.isSyncToEnterprise,
          isAutoLabel: '1'
        }).then(res => {
          this.loading = false
          if (res.code === 200) {
            this.$message.success(res.msg)
            this.back()
          }
        }).catch(() => {
          this.loading = false
        })
      }
    },

    beforeUpload(data) {
      const formData = new FormData()
      formData.append('file', data)
      uploadFile(formData).then(res => {
        if (res.code === 200) {
          const url = window.globalConfig.IMAGE_API + res.data.url
          console.log(url)
          this.form.materialUrl = url
        }
      })
      return false
    },
    addTag() {
      this.tags = this.form.materialTag.join('；')
      this.tagVisible = true
    },
    handleCloseTag(tag) {
      this.form.materialTag.splice(this.form.materialTag.indexOf(tag), 1)
    },
    handleAddTag(value) {
      const arr1 = value.split(/[；;]/g)
      const arr2 = Array.from(new Set(arr1))
      if (arr1.length != arr2.length) {
        this.$message.error('有重复或空标签项')
        return
      } else {
        this.form.materialTag = arr1.filter(item => item !== '' && !item.match(/^[ ]*$/))
        this.tagVisible = false
      }
    },
    back() {
      this.$router.push({
        name: 'Article',
        query: {is_person: this.$route.query.is_person}
      })
    },
    download() {
      const imgUrl = 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
      const a = document.createElement('a')
      fetch(imgUrl)
        .then(res => res.blob())
        .then(blob => {
          a.href = URL.createObjectURL(blob)
          a.download = '123.jpg'
          document.body.appendChild(a)
          a.click()
          window.URL.revokeObjectURL(a.href)
          document.body.removeChild(a)
        })
    },
    changeWang(html) {
      //这里的html是带有标签的
      this.form.content = html
      console.log(this.form.content)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";

.header-btn {
  @include headerBtn;
}

.header {
  font-size: 20px;
  padding: 10px 0;
  margin-bottom: 10px;

  .btn-con {
    float: right;
  }
}

.suggestion {
  font-size: 12px;
  color: #d2d2d2;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

::v-deep {
  .avatar-uploader1 .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader1 .el-upload:hover {
    border-color: #409EFF;
  }
}

.inputFile {
  line-height: 26px;
  margin: 6px 0;
}

.editor{
  z-index: 99;
}
</style>
